set seed 9121995 //Sets seed for replicability


if("`c(os)'"=="Windows"){
	local tableSaveDir = "Tables\"
	local plotSaveDir = "Plots\"
	local pythonSaveDir = "PythonScripts\"
}
else{
	local tableSaveDir = "Tables/"
	local plotSaveDir = "Plots/"
	local pythonSaveDir = "PythonScripts/"
}

//copy default frame over to new frame so as to preserve original data
frame copy default randTreatData
frame change randTreatData
//Drop years in which states were treated
drop if safetyclass=="Had Safety Inspections" & nosafetyind==1

//Establish Control Variable Sets
local Spec1Controls = "c.normYear#i.stateGroup c.quadYear#i.stateGroup asinhMetroPop asinhNonMetroPop asinhMetroInc asinhNonMetroInc logrealmeangasprice logemployment loglicenseddrivers logrealstategdp logroadmileage"
local Spec2Controls = "`Spec1Controls' i.transactionDataDummy"
local Spec3Controls = "`Spec2Controls' i.regDummyExtSpec3"
local Spec4Controls = "`Spec2Controls' i.regDummyExtSpec4"

//Establish ci level
local ciLevel = 95

//Establish Cluster Variable
local clusterVar = "stateGroup year"

//Absorb Vars are always time and state fixed effects
local absorbVars = "ib51.stateGroup ib1995.year"

//Establish reatment variable 
local treatmentVar = "tempRandTreat_res"

//Analysis - Random within Treated State

local numIter = 1000

if("`c(os)'"=="Windows"){
	qui putexcel set "Tables\RandTreatSim.xlsx", sheet("RandTreatRegTreatedStates", replace) modify
}
else{
	qui putexcel set "Tables/RandTreatSim.xlsx", sheet("RandTreatRegTreatedStates", replace) modify
}

qui putexcel A1 = "Iteration"
qui putexcel B1 = "Spec1 Coefficient"
qui putexcel C1 = "Spec2 Coefficient"
qui putexcel D1 = "Spec3 Coefficient"
qui putexcel E1 = "Spec4 Coefficient"
qui putexcel F1 = "Spec1 P"
qui putexcel G1 = "Spec2 P"
qui putexcel H1 = "Spec3 P"
qui putexcel I1 = "Spec4 P"

forvalues iter = 1(1)`numIter'{
	di "Working on Random within Treated State Iteration `iter'"
	preserve //Preserve dataset
	//Set up the random treatment
	qui levelsof statecode if safetyclass=="Had Safety Inspections"
	qui gen tempRandTreatYear = .
	qui gen tempRandTreat = 0

	foreach tempSC in `r(levels)'{
		qui sum year if statecode=="`tempSC'"
		local minYear = `r(min)'+1 //I add one to ensure that the state is treated within the time period and not deemed and ``untreated" state 
		local maxYear = `r(max)'
		local tempYear = runiformint(`minYear', `maxYear')
		
		qui replace tempRandTreatYear = `tempYear' if statecode=="`tempSC'"
		qui replace tempRandTreat = 1 if statecode == "`tempSC'" & year>=tempRandTreatYear
		
	}
	local xlIndex = `iter'+1
	qui putexcel A`xlIndex' = `iter'
	regFWL logregistrations, tempRandTreat, `Spec1Controls', `absorbVars', `clusterVar', _
	qui putexcel B`xlIndex' = _b[mean:`treatmentVar']
	qui test [mean]`treatmentVar'
	qui putexcel F`xlIndex' = `r(p)'
	regFWL logregistrations, tempRandTreat, `Spec2Controls', `absorbVars', `clusterVar', _
	qui putexcel C`xlIndex' = _b[mean:`treatmentVar']
	qui test [mean]`treatmentVar'
	qui putexcel G`xlIndex' = `r(p)'
	regFWL logregistrations, tempRandTreat, `Spec3Controls', `absorbVars', `clusterVar', _
	qui putexcel D`xlIndex' = _b[mean:`treatmentVar']
	qui test [mean]`treatmentVar'
	qui putexcel H`xlIndex' = `r(p)'
	regFWL logregistrations, tempRandTreat, `Spec4Controls', `absorbVars', `clusterVar', _
	qui putexcel E`xlIndex' = _b[mean:`treatmentVar']
	qui test [mean]`treatmentVar'
	qui putexcel I`xlIndex' = `r(p)'

	restore	//Restore to original dataset
}

//Create frame for coefficient data
frame create coefData
frame change coefData
clear

//Load data for the treated state coefficients
if("`c(os)'"=="Windows"){
	import excel "Tables\RandTreatSim.xlsx", sheet("RandTreatRegTreatedStates") firstrow
	local plotSaveDir = "Plots\RandTreatSim\"
}
else{
	import excel "Tables/RandTreatSim.xlsx", sheet("RandTreatRegTreatedStates") firstrow
	local plotSaveDir = "Plots/RandTreatSim/"
}


//Change frame back to altered dataframe
frame change randTreatData
//Analysis - Random throughout all states
//Get probability of having been treated throughout the time period
qui levelsof statecode if safetyclass=="Had Safety Inspections"
local numer = `r(r)'
qui levelsof statecode
local denom = `r(r)'
local probOfTreatment = `numer'/`denom'
//Get the probability of never being treated
qui levelsof statecode if safetyclass=="Has Safety Inspections"
local numer = `r(r)'
qui levelsof statecode
local denom = `r(r)'
local probOfNeverTreated = `numer'/`denom'

//Set output file
if("`c(os)'"=="Windows"){
	qui putexcel set "Tables\RandTreatSim.xlsx", sheet("RandTreatRegAllStates", replace) modify
}
else{
	qui putexcel set "Tables/RandTreatSim.xlsx", sheet("RandTreatRegAllStates", replace) modify
}

qui putexcel A1 = "Iteration"
qui putexcel B1 = "Spec1 Coefficient"
qui putexcel C1 = "Spec2 Coefficient"
qui putexcel D1 = "Spec3 Coefficient"
qui putexcel E1 = "Spec4 Coefficient"
qui putexcel F1 = "Spec1 P"
qui putexcel G1 = "Spec2 P"
qui putexcel H1 = "Spec3 P"
qui putexcel I1 = "Spec4 P"

forvalues iter = 1(1)`numIter'{
	preserve 
	di "Working on Random across All States Iteration `iter'"
	qui gen tempRandTreatYear = .
	qui gen tempRandTreat = 0
	qui levelsof statecode
	foreach tempSC in `r(levels)'{
		local uVal = runiform()
		
		//Determine which type of safety class the state should be assigned
		if(`uVal'<`probOfTreatment'){
			local outcome = "Treated"
		}
		else if(`uVal'>=`probOfTreatment' & `uVal'<(`probOfTreatment'+`probOfNeverTreated')){
			local outcome = "Never Treated"
		}
		else{
			local outcome = "Always Treated"
		}
		
		
		if("`outcome'"=="Treated"){
			qui sum year if statecode=="`tempSC'"
			local minYear = `r(min)'+1 //I add one to ensure that the state is treated within the time period and not deemed and ``untreated" state 
			local maxYear = `r(max)'
			local tempYear = runiformint(`minYear', `maxYear')
			
			qui replace tempRandTreatYear = `tempYear' if statecode=="`tempSC'"
			qui replace tempRandTreat = 1 if statecode == "`tempSC'" & year>=tempRandTreatYear
		}
		else if("`outcome'"=="Always Treated"){
			qui replace tempRandTreat = 1 if statecode == "`tempSC'"
		}
	}
	
	local xlIndex = `iter'+1
	qui putexcel A`xlIndex' = `iter'
	regFWL logregistrations, tempRandTreat, `Spec1Controls', `absorbVars', `clusterVar', _
	qui putexcel B`xlIndex' = _b[mean:`treatmentVar']
	qui test [mean]`treatmentVar'
	qui putexcel F`xlIndex' = `r(p)'
	regFWL logregistrations, tempRandTreat, `Spec2Controls', `absorbVars', `clusterVar', _
	qui putexcel C`xlIndex' = _b[mean:`treatmentVar']
	qui test [mean]`treatmentVar'
	qui putexcel G`xlIndex' = `r(p)'
	regFWL logregistrations, tempRandTreat, `Spec3Controls', `absorbVars', `clusterVar', _
	qui putexcel D`xlIndex' = _b[mean:`treatmentVar']
	qui test [mean]`treatmentVar'
	qui putexcel H`xlIndex' = `r(p)'
	regFWL logregistrations, tempRandTreat, `Spec4Controls', `absorbVars', `clusterVar', _
	qui putexcel E`xlIndex' = _b[mean:`treatmentVar']
	qui test [mean]`treatmentVar'
	qui putexcel I`xlIndex' = `r(p)'
	
	restore
}

//Change frame for coefficient data
frame change coefData
clear

//Load data for the treated state coefficients
if("`c(os)'"=="Windows"){
	import excel "Tables\RandTreatSim.xlsx", sheet("RandTreatRegAllStates") firstrow
	local plotSaveDir = "Plots\RandTreatSim\"
}
else{
	import excel "Tables/RandTreatSim.xlsx", sheet("RandTreatRegAllStates") firstrow
	local plotSaveDir = "Plots/RandTreatSim/"
}

//Revert back to default frame
frame change default
